package com.example.forum.services.impl;

import com.example.forum.common.AppResult;
import com.example.forum.common.enums.MessageReplyStatus;
import com.example.forum.common.enums.MessageStatus;
import com.example.forum.common.enums.ResultCode;
import com.example.forum.common.validation.ValidationUtils;
import com.example.forum.dao.MessageMapper;
import com.example.forum.exception.ApplicationException;
import com.example.forum.model.Message;
import com.example.forum.model.User;
import com.example.forum.services.IMessageService;
import com.example.forum.services.IUserService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @author hanzishuai
 * @date 2025/4/13 14:04
 * @Description
 */
@Slf4j
@Service
public class MessageServiceImpl implements IMessageService {

    @Resource
    private MessageMapper messageMapper;

    @Resource
    private IUserService userService;

    @Override
    public Message selectById(Long id) {
        // 校验
        ValidationUtils.id(id, "站内信 Id");

        Message message = messageMapper.selectByPrimaryKey(id);

        return message;
    }

    @Override
    public void create(Message message) {
        // 非空校验
        if (message == null || message.getPostUserId() == null || message.getPostUserId() < 0
                || message.getReceiveUserId() == null || message.getReceiveUserId() < 0
                || !StringUtils.hasLength(message.getContent())) {
            log.warn("{}", ResultCode.FAILED_PARAMS_VALIDATE);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        // 校验发送者是否存在
        User postUser = userService.selectById(message.getPostUserId());
        ValidationUtils.exists(postUser);

        // 校验接收者是否存在
        User user = userService.selectById(message.getReceiveUserId());
        ValidationUtils.exists(user);

        // 设置默认值
        message.setState(MessageReplyStatus.NOT_READ.getStatus());
        message.setDeleteState(MessageStatus.NOT_DELETE.getStatus());

        // 设置创建和更新时间
        LocalDateTime dateTime = LocalDateTime.now();
        message.setCreateTime(dateTime);
        message.setUpdateTime(dateTime);

        // 调用 DAO
        int row = messageMapper.insertSelective(message);
        ValidationUtils.singleRowAffected(row);


    }

    @Override
    public Integer selectUnreadCount(Long receiveUserId) {
        // 非空校验
        ValidationUtils.id(receiveUserId, "接收站内信的用户 Id");


        // 调用 DAO
        Integer count = messageMapper.selectUnreadCount(receiveUserId);

        // 正常的查询是不可能出现 null 的
        if (count == null) {
            log.warn("{}", ResultCode.ERROR_SERVICES);
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }

        return count;
    }

    @Override
    public List<Message> selectByReceiveUserId(Long receiveUserId) {

        // 非空校验
        ValidationUtils.id(receiveUserId, "接收站内信的用户 Id");

        List<Message> messages = messageMapper.selectByReceiveUserId(receiveUserId);

        return messages;
    }

    @Override
    public void updateStateById(Long id, Byte state) {
        // 校验 state 是否合法
        boolean flag = false; // 默认不合法
        for (MessageReplyStatus replyStatus : MessageReplyStatus.values()) {
            if (state == replyStatus.getStatus()) {
                flag = true;
                break;
            }
        }
        if (!flag) {
            log.info("state 不合法，state：{}", state);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        // 校验
        ValidationUtils.id(id, "站内信 Id");


        // 构造更新对象
        Message updateMessage = new Message();
        updateMessage.setId(id);
        updateMessage.setState(state);
        updateMessage.setUpdateTime(LocalDateTime.now());

        // 调用 DAO
        int row = messageMapper.updateByPrimaryKeySelective(updateMessage);

        ValidationUtils.singleRowAffected(row);

    }

    @Override
    @Transactional
    public void reply(Long repliedId, Message message) {
        ValidationUtils.id(repliedId, "回复的站内信 Id");


        Message existsMessage = messageMapper.selectByPrimaryKey(repliedId);

        // 校验 repliedId 对应的站内信是否存在
        ValidationUtils.exists(existsMessage);

        // 校验站内信状态是否合法
        ValidationUtils.banned(existsMessage);


        // 更新状态为已回复
        updateStateById(repliedId, MessageReplyStatus.IS_REPLIED.getStatus());

        // 把回复内容写入数据库
        create(message);
    }


}



















